package utils

import (
	"bytes"
	"crypto/aes"
	"encoding/base64"
	"fmt"
	"gogo/log"
	"os"
	"testing"
)

// ECB模式解密
func (c *GoGo_Utils_Class) ECBDecrypt(crypted, key []byte) ([]byte, error) {
	if !c.validKey(key) {
		return nil, fmt.Errorf("秘钥长度错误,当前传入长度为 %d", len(key))
	}
	if len(crypted) < 1 {
		return nil, fmt.Errorf("源数据长度不能为0")
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(crypted)%block.BlockSize() != 0 {
		return nil, fmt.Errorf("源数据长度必须是 %d 的整数倍，当前长度为：%d", block.BlockSize(), len(crypted))
	}
	var dst []byte
	tmpData := make([]byte, block.BlockSize())

	for index := 0; index < len(crypted); index += block.BlockSize() {
		block.Decrypt(tmpData, crypted[index:index+block.BlockSize()])
		dst = append(dst, tmpData...)
	}
	dst, err = c.PKCS5UnPadding(dst)
	if err != nil {
		return nil, err
	}
	return dst, nil
}

// ECB模式加密
func (c *GoGo_Utils_Class) ECBEncrypt(src, key []byte) ([]byte, error) {
	if !c.validKey(key) {
		return nil, fmt.Errorf("秘钥长度错误, 当前传入长度为 %d", len(key))
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(src) < 1 {
		return nil, fmt.Errorf("源数据长度不能为0")
	}
	src = c.PKCS5Padding(src, block.BlockSize())
	if len(src)%block.BlockSize() != 0 {
		return nil, fmt.Errorf("源数据长度必须是 %d 的整数倍，当前长度为：%d", block.BlockSize(), len(src))
	}
	var dst []byte
	tmpData := make([]byte, block.BlockSize())
	for index := 0; index < len(src); index += block.BlockSize() {
		block.Encrypt(tmpData, src[index:index+block.BlockSize()])
		dst = append(dst, tmpData...)
	}
	return dst, nil
}

// PKCS5填充
func (c *GoGo_Utils_Class) PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

// 去除PKCS5填充
func (c *GoGo_Utils_Class) PKCS5UnPadding(origData []byte) ([]byte, error) {
	length := len(origData)
	unpadding := int(origData[length-1])

	if length < unpadding {
		return nil, fmt.Errorf("invalid unpadding length")
	}
	return origData[:(length - unpadding)], nil
}

// 秘钥长度验证
func (c *GoGo_Utils_Class) validKey(key []byte) bool {
	k := len(key)
	switch k {
	default:
		return false
	case 16, 24, 32:
		return true
	}
}

func (c *GoGo_Utils_Class) TestAes(t *testing.T) {
	srcData := "hello world !"
	key := []byte("abcdabcdabcdabcdabcdabcdabcdabcd")
	//测试加密
	encData, err := c.ECBEncrypt([]byte(srcData), (key))
	if err != nil {
		t.Errorf(err.Error())
		return
	}

	//测试解密
	decData, err := c.ECBDecrypt(encData, key)
	if err != nil {
		t.Errorf(err.Error())
		return
	}
	log.This().DebugF("srcData: %s\n", string(decData))
}

func (c *GoGo_Utils_Class) DoAESFile(key []byte, need_aes_file, after_aes_file string) {
	if _, err := os.Stat(need_aes_file); os.IsNotExist(err) {
		return
	}
	buf, err := os.ReadFile(need_aes_file)
	if err != nil {
		return
	}

	if len(buf) == 0 {
		return
	}

	encData, err := c.ECBEncrypt(buf, (key))
	if err != nil {
		log.This().ErrorF("ParseWithPath ECBEncrypt err: %v", err)
		return
	}

	encodeString := base64.StdEncoding.EncodeToString(encData)

	if c.FileExist(after_aes_file) {
		c.FileDel(after_aes_file)
	}

	f, err := os.OpenFile(after_aes_file, os.O_CREATE|os.O_WRONLY, 0o644)
	if err != nil {
		log.This().ErrorF("can't open file %s: %s", after_aes_file, err.Error())
		return
	}
	f.WriteString(encodeString)
	f.Close()
}
